package gtug.duesseldorf.client.ui;

import gtug.duesseldorf.client.Wave_webclient;
import gtug.duesseldorf.client.model.ClientWaveId;
import gtug.duesseldorf.client.model.ClientWaveList;
import gtug.duesseldorf.client.util.StringUtils;

import java.util.HashMap;

import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.user.client.ui.Composite;

public class WaveList extends Composite {

	private final Wave_webclient m_client;
	private final DCListBox m_slWaves = new DCListBox();

	public WaveList(Wave_webclient client) {
		m_client = client;

		m_slWaves.setVisibleItemCount(10);
		initWidget(m_slWaves);

		m_slWaves.addDoubleClickHandler(new DoubleClickHandler() {
			public void onDoubleClick(DoubleClickEvent event) {
				m_client.openWave(getWaveId());
			}
		});
	}

	/**
	 * return the current selected waveId or null
	 * 
	 * @return
	 */
	public String getWaveId() {
		int selIndex = m_slWaves.getSelectedIndex();
		if (selIndex != -1) {
			String id = m_slWaves.getValue(selIndex);
			return id;
		} else {
			return null;
		}
	}

	public void setWaveList(ClientWaveList clientWaveList) {

		if (clientWaveList.isNewList()) {
			clear();

			for (ClientWaveId wave : clientWaveList.getWaveList()) {
				if (isVisibleWave(wave) == false) {
					continue;
				}

				m_slWaves.addItem(wave.getNameAndDigest(), wave.getId());
			}
		} else {

			// copy slWaves#itemValues to map for faster access
			HashMap<String, Integer> itemMap = new HashMap<String, Integer>();

			for (int i = 0, iSiz = m_slWaves.getItemCount(); i < iSiz; i++) {
				itemMap.put(m_slWaves.getValue(i), i);
			}

			for (ClientWaveId wave : clientWaveList.getWaveList()) {
				if (isVisibleWave(wave) == false) {
					continue;
				}

				Integer index = itemMap.get(wave.getId());

				String name = "(" + wave.getId() + ") " + StringUtils.abbreviate(wave.getDigest(), 15);

				if (index == null) {
					m_slWaves.addItem(name, wave.getId());
				} else {
					m_slWaves.setItemText(index.intValue(), name);
				}
			}
		}
	}

	/**
	 * dont show the indexwave
	 * 
	 * @param wave
	 * @return
	 */
	private boolean isVisibleWave(ClientWaveId wave) {
		return (false == "indexwave".equals(wave.getId()));
	}

	public void setOpenWave(ClientWaveId clientWaveId) {
		if (clientWaveId != null) {
			String id = clientWaveId.getId();
			for (int i = 0, iSiz = m_slWaves.getItemCount(); i < iSiz; i++) {
				if (id.equals(m_slWaves.getValue(i))) {
					m_slWaves.setSelectedIndex(i);
					break;
				}
			}
		}
	}

	public void clear() {
		m_slWaves.clear();
	}

}
